package cn.ihoway.game;

import cn.ihoway.annotation.Processor;
import cn.ihoway.common.CommonProcessor;
import cn.ihoway.entity.Allocation;
import cn.ihoway.entity.Room;
import cn.ihoway.game.io.GameStartInput;
import cn.ihoway.game.io.GameStartOutput;
import cn.ihoway.redis.AllocationRedis;
import cn.ihoway.redis.CharacterRedis;
import cn.ihoway.redis.RoomRedis;
import cn.ihoway.socket.GameSessionManager;
import cn.ihoway.type.StatusCode;
import cn.ihoway.util.HowayLog;
import cn.ihoway.util.HowayMessage;
import cn.ihoway.util.HowayWsResult;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 房主点击开始游戏
 * 房间状态不为1不可以开始游戏
 * 对房间内所有玩家分配角色
 * 随机指定房间内设置卧底数量的卧底玩家
 * 房间状态设置为2，此时不允许其他玩家加入房间
 * 告诉全部玩家各自身份、角色，告知游戏已经开始
 */
@Processor(name = "GameStartProcessor")
public class GameStartProcessor  extends CommonProcessor<GameStartInput, GameStartOutput> {
    private final HowayLog logger = new HowayLog(GameStartProcessor.class);
    private final AllocationRedis allocationRedis = new AllocationRedis();
    private final RoomRedis roomRedis = new RoomRedis();
    private final CharacterRedis characterRedis = new CharacterRedis();

    @Override
    protected StatusCode dataCheck(GameStartInput input){
        return StatusCode.SUCCESS;
    }
    
    @Override
    protected HowayWsResult process(GameStartInput input, GameStartOutput output) throws IOException, InterruptedException {
        Allocation allocation = allocationRedis.getBySessionId(input.inChomm.sessionId);
        if(allocation == null){
            return HowayWsResult.createFailResult(StatusCode.ROOM_EMPTY,output);
        }
        if(!"1".equals(allocation.getPlayerId())){
            return HowayWsResult.createFailResult(StatusCode.ILLEGAL_OPERATION,"你不是房主",output);
        }
        Room room = roomRedis.get(allocation.getRoomId());
        if(room.getStatus() != 1){
            return HowayWsResult.createFailResult(StatusCode.ILLEGAL_OPERATION,"检查房间状态",output);
        }
        //当前人数小于设置的卧底人数
        if(room.getCurrentNum() <= room.getMinNum()){
            return HowayWsResult.createFailResult(StatusCode.ILLEGAL_OPERATION,"房间人数小于"+ room.getMinNum() +"人,无法游戏",output);
        }
        int num = room.getCurrentNum();
        ArrayList<Integer> list = new ArrayList<>();
        Random rand = new Random();
        while(list.size() < num){
            Integer value = rand.nextInt(characterRedis.size()) + 1;
            if(!list.contains(value)){
                list.add(value);
            }
        }
        //随机产生卧底的id
        ArrayList<Integer> moleList = new ArrayList<>();
        while(moleList.size() <= room.getMoleNum()){
            Integer value = rand.nextInt(room.getCurrentNum()) + 1;
            if(!moleList.contains(value)){
                moleList.add(value);
            }
        }
        //赋值给各个用户
        int index = 0;
        int pos = 0;
        List<Allocation> allocationList = allocationRedis.getByRoomId(allocation.getRoomId());
        for (Allocation user : allocationList){
            Integer id = list.get(index);
            if(pos < moleList.size() && Integer.parseInt(user.getPlayerId()) == moleList.get(pos)){
                pos++;
                user.setPlayerType(2);
            }
            user.setCharacterId(id);
            index++;
            allocationRedis.update(user);
            WebSocketSession session = GameSessionManager.get(user.getSessionId());
            logger.info(" session " + session);
            if(session != null){

                if(user.getPlayerType() == 2){
                    //todo 告知队友角色信息

                    HowayMessage message = new HowayMessage("你的身份是卧底,存活到最后且杀死其他玩家获胜。");
                    session.sendMessage(new TextMessage(message.toString()));
                }else {
                    HowayMessage message = new HowayMessage("你的角色是" + characterRedis.get(id).getName());
                    session.sendMessage(new TextMessage(message.toString()));
                    message = new HowayMessage("你的身份是普通玩家,投票解决全部卧底获胜。");
                    session.sendMessage(new TextMessage(message.toString()));
                }
            }
        }

        int seconds = 10;
        while(seconds > 0){
            for (Allocation user : allocationList){
                WebSocketSession session = GameSessionManager.get(user.getSessionId());
                HowayMessage message = new HowayMessage("倒计时 " + seconds + " 秒");
                session.sendMessage(new TextMessage(message.toString()));
            }
            Thread.sleep(1000);
            seconds--;
        }
        room.setStatus(2);
        roomRedis.put(room.getId(),room);

        return HowayWsResult.createSuccessResult(output);
    }
}